package com.wxq.schoolmap;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.XmlDom;
import com.lxr.activity.SiteListActivity;
import com.lxr.activity.HorizontalListView;
import com.lxr.activity.ListviewAdapter;
import com.wxq.draw.DrawConstants;
import com.wxq.draw.DrawDBTool;
import com.wxq.draw.MapLayout;
import com.wxq.schoolmap.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class DrawActivity extends Activity {
	
	protected Button zoomInButton,zoomOutButton;//地图放大缩小按钮
	protected Button routelast, routenext;//路径前进后退按钮
	protected Button wcButton;//公共设施按钮
	protected Button menuButton;//查找按钮
	protected Button removeButton;//清空按钮
    protected Button addButton;
	protected Button routeBtn;// 查找路径按钮
	protected Button backtoschoolBtn;//返回按钮
	protected TextView middletext;//地点信息文字
	protected HorizontalListView  floormenulist;//楼层横向list
	protected ListView menulist;//公共设施列表
	
	protected ProgressDialog m_pDialog;
	protected int m_count=0;
	protected Boolean Webconnected=false;
	
	protected Boolean goto1=false;//是否已标记终点
	protected Boolean from1=false;//是否已标记起点
	protected PointF fromCoord,gotoCoord;//起点终点坐标
	protected String fromfloor,gotofloor;//起点终点
	protected String fromDBpath,gotoDBpath;//起点终点所属地图
	protected String Mallid="";
	protected String MallDBpath="phone3";
	protected List<Map<String, Object>> wclist;
	//protected List<String> wclist;
	protected AQuery aq;

	protected Boolean weather_route=false;//是否处于显示路径状态
	
	
	
	protected MapLayout mapLayout;
	protected String floorName;
	Map<String,String> spotid=new HashMap<String, String>();
	{
		spotid.put("899EC5AB-B9E7-444C-98A2-F76CFA223A47","61cbcb8f-b689-443e-987e-c96f71f4723e");
		spotid.put("460919D6-D356-43C0-90F3-978336ED68EE","b0a866dd-d077-45e7-b738-149cf684cb56");
		spotid.put("C38A52A6-4E85-4937-8522-FA7997090DB3","c059c81f-f359-4f0c-8ad0-cb929d19caf3");
		spotid.put("52EC1285-DE91-4A21-86D8-FD85BDC236F2","db2d5852-c36d-48c2-a796-b8c48b2421c1");
		spotid.put("E9F6A2DE-EADC-45AF-A42E-C7458A401339","0d3e625f-a04c-49ea-9373-ec326e54c7e1");
		spotid.put("BE4DF5A1-9EDC-41BE-8813-72288B25fAD5","7e28fd7b-42d4-4d31-b9e7-833fc35650b4");
		spotid.put("5DA81C33-71DB-4EA8-8C39-F6B5A0ECA83F","a3e7ea86-c2a8-4e90-830b-d9e8ee590aa6");
		spotid.put("07B7D54C-E436-4C0B-89F7-48810E29C5CA","phone3");
		spotid.put("EFF6607F-CE46-400F-8CB1-6A74A993B8E3","7e28fd7b-42d4-4d31-b9e7-833fc35650b4");
		spotid.put("C38A52A6-4E85-4937-8522-FA7997090BD3" ,"c059c81f-f359-4f0c-8ad0-cb929d19caf3");
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.draw_view);
		
		wcButton = (Button) findViewById(R.id.wc);
		menuButton = (Button) findViewById(R.id.menu);
		zoomInButton = (Button) findViewById(R.id.zoomInBtn);
		zoomOutButton = (Button) findViewById(R.id.zoomOutBtn);
		routelast = (Button) findViewById(R.id.lastBtn);
		routenext = (Button) findViewById(R.id.nextBtn);
		addButton=(Button) findViewById(R.id.addSpotBtn);
		removeButton=(Button) findViewById(R.id.removeall);
		backtoschoolBtn=(Button) findViewById(R.id.backtoschoolmap);
		
		aq= new AQuery(this);
		
		//backtoschoolBtn.setVisibility(View.INVISIBLE);
		DrawDBTool dbTool = new DrawDBTool(this);
		Mallid=dbTool.getMAllid(MallDBpath);
		
		mapLayout = (MapLayout) findViewById(R.id.mapLayout);
		
		 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	     StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
		
		Intent intent = getIntent();
		floorName = intent.getStringExtra("FloorName");		
		mapLayout.loaingSchoolMap();//此时地图控件显示图像。
		
		fromCoord= new PointF();
		gotoCoord = new PointF();
		
		setAllButtom();
		
	}
	
	private void addfloorlist(String filename){
		 DrawDBTool dbTool;
		 dbTool = new DrawDBTool(DrawActivity.this);
		 dbTool.setDBpath(filename);
         List<String> floornameList= dbTool.getFloorNames();
         dbTool.close();
		 //final ArrayAdapter<String> flooradapter = new ArrayAdapter<String>(this, R.layout.simple_textview2, floornameList);
         final ListviewAdapter flooradapter = new ListviewAdapter(this, (ArrayList<String>) floornameList);  
         floormenulist.setAdapter(flooradapter);
         flooradapter.setSelectedPosition(floornameList.indexOf(floorName));
		 floormenulist.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					Log.d("lxr",(String) flooradapter.getItem(position));
					floorName=(String) flooradapter.getItem(position);
					flooradapter.setSelectedPosition(position);
					flooradapter.notifyDataSetChanged();
					changefloor();
				}
				});
	}
	private void addwclist(){
		// String[] nameList= new String[] {"楼梯","电梯","扶梯","出入口","ATM","洗手间","休息区","邮局"};
		 DrawDBTool dbTool = new DrawDBTool(this);
		 wclist = dbTool.getwclist(MallDBpath,floorName);
		 final SimpleAdapter adapter = new SimpleAdapter(DrawActivity.this, wclist, R.layout.wc_list_item, new String[] { "Type","num"}, new int[] { R.id.Type,R.id.num});
		// final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_textview1,  wclist);
			menulist.setAdapter(adapter);
	        menulist.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					DrawDBTool dbTool;
					dbTool = new DrawDBTool(DrawActivity.this);
					dbTool.setDBpath(MallDBpath);
					List<Map<String,Object>> wcList=dbTool.getwcNUM(floorName,wclist.get(position).get("Type").toString());
					//List<Map<String,Object>> wcList=dbTool.getwcNUM(floorName,wclist.get(position));
					mapLayout.wcpoint(wcList , R.drawable.da_marker_red);
			     	mapLayout.hidemenu();
					//dbTool.close();
					}
				});
		}
	
	private void dialogShowbuilding() {   
	new AlertDialog.Builder(this)  
	    .setTitle("查看建筑")  
	    .setMessage("您确定要查看“"+mapLayout.getspotName()+"”吗？")  
	    .setPositiveButton  
	            ("查看详情", new DialogInterface.OnClickListener()  
	                { public void onClick(DialogInterface dialog, int which) 
	                    {       
	            		String spotID = mapLayout.getCurrentSpotID();
	    				if (TextUtils.isEmpty(spotID)) {
	    					//Log.d("wxq", "当前spotID = "+spotID);
	    				}
	    				else {

	    					Intent newIntent = new Intent();	    					
	    					newIntent.setClass(DrawActivity.this, SpotDetailActivity.class);	    					
	    					newIntent.putExtra("spotId", spotID);
	    					newIntent.putExtra("MallDBpath", MallDBpath);
	    					DrawActivity.this.startActivity(newIntent);
	    				}
	                    }})
	    .setNegativeButton  
	            ("进入地图", new DialogInterface.OnClickListener()  
	                { public void onClick(DialogInterface dialog, int which){
	                	String spotID = mapLayout.getCurrentSpotID();
	                	DrawDBTool  dbTool = new DrawDBTool(DrawActivity.this);
	                	changeDBmap(dbTool.getunityid(spotID),"Floor1");
	                }})  
	    .show();  
	}  
	
	protected void changeDBmap(String ID,String floor){
		floorName=floor;
	    MallDBpath=ID;	
	    Log.d("lxr", ID);
	    File dbFile = new File(android.os.Environment.getExternalStorageDirectory()+DrawConstants.DBFolder+ID+".db");
	    if(!dbFile.exists()){
			try {
				
				down_file_2(ID,"http://10.103.240.66/map/"+ID+".db",android.os.Environment.getExternalStorageDirectory()+DrawConstants.DBFolder);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				Toast toast = Toast.makeText(this, e1.toString(), Toast.LENGTH_SHORT); 
		    	  toast.setGravity(0|0, 80, 80); 
		    	  toast.setMargin(-0.5f, 0f); 
		    	  toast.show();
			}
		}else{
			mapLayout.changemap(MallDBpath, floorName);
			addfloorlist(MallDBpath);
			addwclist();
			DrawDBTool dbTool = new DrawDBTool(this);
			Mallid=dbTool.getMAllid(MallDBpath);
			mapLayout.hideAll();
			}
		if(!MallDBpath.equals("phone3")){
		//backtoschoolBtn.setVisibility(View.VISIBLE);
		floormenulist.setVisibility(View.VISIBLE);}
		else{
			//backtoschoolBtn.setVisibility(View.INVISIBLE);
			floormenulist.setVisibility(View.INVISIBLE);
		}
		mapLayout.hideAll(); 
		if(floorName.equals(fromfloor)&&fromDBpath.equals(MallDBpath)&&from1==true){
     		mapLayout.pinfromAtMapWithMapCoord(fromCoord);
     		showfindroute(fromCoord);
     	}
		if(floorName.equals(gotofloor)&&gotoDBpath.equals(MallDBpath)&&goto1==true){
     		mapLayout.pingotoAtMapWithMapCoord(gotoCoord);
     		showfindroute(gotoCoord);
     	}
		
     		if(weather_route==true){
     		RouteOfMap();//当属于显示路径状态时，显示该地图上应有的路径
     	}	
     	
	}
	
	protected void changefloor(){		
		mapLayout.changemap(MallDBpath,floorName);
     	mapLayout.hideAll();   	
     	addwclist();
     	if(floorName.equals(fromfloor)&&fromDBpath.equals(MallDBpath)&&from1==true){
     		mapLayout.pinfromAtMapWithMapCoord(fromCoord);
     		showfindroute(fromCoord);
     	}
     	if(floorName.equals(gotofloor)&&gotoDBpath.equals(MallDBpath)&&goto1==true){
     		mapLayout.pingotoAtMapWithMapCoord(gotoCoord);
     		showfindroute(gotoCoord);
     	}
     		if(weather_route==true){
     		mapLayout.DrawRoute(floorName);
     		mapLayout.updatedrawtoroute();
     	  }	
	} 
	
	protected void showfindroute( PointF hy){
		if(from1==true&&goto1==true){
			mapLayout.showOverlay2(hy);
		}	
	}
	
	public void setAllButtom() {
		wcButton.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {
				mapLayout.hideOverlay();
				mapLayout.showmenu(DrawActivity.this);
			}
		});
		menuButton.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
		    	intent.setClass(DrawActivity.this, SiteListActivity.class);
		    	intent.putExtra("MallDBpath",MallDBpath);
		    	intent.putExtra("FloorName",floorName);
		    	startActivityForResult(intent, 0);  
			}
		});
		backtoschoolBtn.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {	
				if(!MallDBpath.equals("phone3")){
				  changeDBmap("phone3","Floor0");}
				else{
				  showToast("当前为校园平面地图，无法返回。\n 点击建筑名称可以进入建筑室内地图哦！");
		    	  }
			}
		});
		zoomInButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				zoomIn();
			}
		});
		zoomOutButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				zoomOut();
			}
		});
		routelast.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String name=mapLayout.lastRoutePiont();
				if(!name.equals("starting")){
					if(!name.equals(floorName)){
						floorName=name;
						changefloor();
						showToast("切换楼层");
					}
					mapLayout.showrouteinfo();
			    }else if(name.equals("starting")&&!gotoDBpath.equals(MallDBpath)){
			    	if(!MallDBpath.equals("phone3")){
			    		changeDBmap("phone3","Floor0");
			    		showToast("进入室外地图");
			    	}else{
			    		changeDBmap(fromDBpath,"Floor1");
			    		showToast("进入室内地图");
			    	}
			    	mapLayout.lastRoutePiont();
			    	mapLayout.showrouteinfo();
			    }else{
			    	//回退到到起点了
			    }
			}
		});
		routenext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String name=mapLayout.nextRoutePiont();
				if(!name.equals("ending")){
					if(!name.equals(floorName)){
						floorName=name;
						changefloor();
						showToast("切换楼层");
					}
					mapLayout.showrouteinfo();
				}else if(name.equals("ending")&&!gotoDBpath.equals(MallDBpath)){
                    if(!MallDBpath.equals("phone3")){
                    	changeDBmap("phone3","Floor0");
                    	showToast("进入室外地图");
			    	}else{
			    		changeDBmap(gotoDBpath,"Floor1");
			    		showToast("进入室内地图");
			    	}
                    mapLayout.nextRoutePiont();
			    	mapLayout.showrouteinfo();
				}else{
			    	//前进道终点了
			    }
			}
		});
		removeButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mapLayout.hideAll();
				goto1=false;
				from1=false;
				weather_route=false;
			}
		});
	 addButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent newIntent = new Intent();
				newIntent.setClass(DrawActivity.this, AddSpotActivity.class);
				newIntent.putExtra("floorName", floorName);
				newIntent.putExtra("MallDBpath", MallDBpath);
				newIntent.putExtra("X_Coord", mapLayout.getOverlayMapCoord().x+"");
				newIntent.putExtra("Y_Coord", mapLayout.getOverlayMapCoord().y+"");
				DrawActivity.this.startActivity(newIntent);
			}
		});

		Button pinRightBtn = (Button) mapLayout.findViewById(R.id.rightBtn);
		pinRightBtn.setText("选终点");
		pinRightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(weather_route==true){
					goto1=false;
					from1=false;
					weather_route=false;
					mapLayout.hideroute();
					mapLayout.hideroutepiont();
					mapLayout.hiderouteinfo();
				}
				gotoCoord.x = mapLayout.getOverlayMapCoord().x;
				gotoCoord.y = mapLayout.getOverlayMapCoord().y;
				gotofloor= floorName;
				gotoDBpath= MallDBpath;
				mapLayout.pingotoAtMapWithMapCoord(gotoCoord);
				mapLayout.hideOverlay();
				goto1=true;
				showfindroute(gotoCoord);
			}
		});
		//点击进入界面
		middletext= (TextView) mapLayout.findViewById(R.id.titleView);
		middletext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//if(spotid.containsValue(mapLayout.getCurrentSpotID())){	
					dialogShowbuilding();
//				}else{
//					String spotID = mapLayout.getCurrentSpotID();
//    				if (TextUtils.isEmpty(spotID)) {
//    					//Log.d("wxq", "当前spotID = "+spotID);
//    				}
//    				else {
//    					Intent newIntent = new Intent();
//    					newIntent.setClass(DrawActivity.this, SpotDetailActivity.class);
//    					newIntent.putExtra("spotId", spotID);
//    					newIntent.putExtra("MallDBpath", MallDBpath);
//    					DrawActivity.this.startActivity(newIntent);
//    				}
//				}
			}
		});
		
		//标记起点
		Button pinLeftBtn = (Button) mapLayout.findViewById(R.id.leftBtn);
		pinLeftBtn.setText("选起点");	
		pinLeftBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(weather_route==true){
					goto1=false;
					from1=false;
					weather_route=false;
					mapLayout.hideroute();
					mapLayout.hideroutepiont();
					mapLayout.hiderouteinfo();
				}
					fromCoord.x = mapLayout.getOverlayMapCoord().x;
					fromCoord.y = mapLayout.getOverlayMapCoord().y;
					fromfloor= floorName;
					fromDBpath= MallDBpath;
					mapLayout.pinfromAtMapWithMapCoord(fromCoord);
					mapLayout.hideOverlay();
					from1=true;
					showfindroute(fromCoord);
			}
		});
		//显示路径的按钮
		routeBtn = (Button) mapLayout.findViewById(R.id.routestart);	
		routeBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {			
				
					if(from1==true&&goto1==true){
						 weather_route=true;
						//mapLayout.hideOverlay2();						
						if(!fromDBpath.equals(MallDBpath)){	
							changeDBmap(fromDBpath,fromfloor);
						}else{
							RouteOfMap();
						}
				}
			}
		});
		//公共设施
		  menulist = (ListView) findViewById(R.id.menulist);
		 addwclist();
	     //楼层切换
	     floormenulist = (HorizontalListView ) findViewById(R.id.HorizonView);	     
	    // addfloorlist("phone3");
	}
	
	public void zoomIn() {
		mapLayout.zoomIn();
	}
	
	public void zoomOut() {
		mapLayout.zoomOut();
	}

	@Override
	protected void onDestroy() {
		mapLayout.close();
		super.onDestroy();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
	    	Bundle b=data.getExtras(); 
	    	if(b.containsKey("unit_id")){
	    		Log.d("lxr","onActivityResult:ohyeah im get in again!!!!");
	    		String id=b.getString("unit_id");
	    		String floor=b.getString("floor_id");
	    		Log.d("lxr","onActivityResult:ohyeah id="+id+"   spotid= "+spotid.get(id)+floor);
	    		//changeDBmap(spotid.get(id),floor);
	    		changeDBmap(id,floor);
	    	}
	    	float X=b.getFloat("X");
	    	float Y=b.getFloat("Y");
	     	mapLayout.sitepoint(X,Y);
		    break;
		default:
		    break;
		}
	}

		/*List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pionttext","从星星KTV出门左转!标题要长" );  map.put("Coord_X", 90);  map.put("Coord_Y", 17);  list.add(map); map = new HashMap<String, Object>(); 
		map.put("pionttext","看见厕所右转回头" );  map.put("Coord_X", 100);  map.put("Coord_Y", 30);  list.add(map); map = new HashMap<String, Object>();
		map.put("pionttext","啊啊？？这里是哪里？！" );  map.put("Coord_X", 75);  map.put("Coord_Y", 50);  list.add(map); map = new HashMap<String, Object>();
		map.put("pionttext","超市发找到了!" );  map.put("Coord_X", 80);  map.put("Coord_Y", 65);  list.add(map); map = new HashMap<String, Object>();
	   */
	
	/*	public List<Map<String,Object>> readXML( PointF fromis, PointF gotois,String ffloor,String gfloor,String path) {
	List<Map<String, Object>> persons = new ArrayList<Map<String,Object>>();	
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	try {
    	DocumentBuilder builder = factory.newDocumentBuilder();
    	String url="http://10.103.241.194:55555/xml?2&"+String.valueOf(fromis.x)+","+String.valueOf(fromis.y)+","+ffloor+"&"+String.valueOf(gotois.x)+","+String.valueOf(gotois.y)+","+gfloor+"&"+Mallid;
    	Log.d("lxr",url);
    	Document dom = builder.parse(url);
    	//Handler handler = new Handler();
    	//builder.
	    Element root = dom.getDocumentElement();
	    NodeList items = root.getElementsByTagName("POINT");//查找所有person节点
		
	  String x = null,y = null,name = null,floor = null,x1 = null,y1 = null,name1 = null,floor1 = null;
	  for (int i = 0; i < items.getLength(); i++) { 
		Element personNode = (Element) items.item(i);
    	Map<String, Object> map = new HashMap<String, Object>();
    	NodeList childsNodes = personNode.getChildNodes();
     	for (int j = 0; j < childsNodes.getLength(); j++) {
        	Node node = (Node) childsNodes.item(j); //判断是否为元素类型          	
        	if(node.getNodeType() == Node.ELEMENT_NODE){ 
         		Element childNode = (Element) node;
	        	if ("X".equals(childNode.getNodeName())) { 
        		   x=childNode.getFirstChild().getNodeValue();  
        	   } else if ("Y".equals(childNode.getNodeName())) {
	        	  y=childNode.getFirstChild().getNodeValue();
        	   } else if ("NAME".equals(childNode.getNodeName())) {
	        	  name=childNode.getFirstChild().getNodeValue();
	           }else if ("FLOOR".equals(childNode.getNodeName())) {
	        	  floor=childNode.getFirstChild().getNodeValue();
	           }		
        	}	
	   }
     	if(!x.equals(x1)||!y.equals(y1)||!name.equals(name1)||!floor.equals(floor1)){
     		if(x.equals(x1))Log.d("lxr",x1+"AND"+x+"truth");else Log.d("lxr",x1+"AND"+x+"false");
     		    x1=x;y1=y;name1=name;floor1=floor;
     		    map.put("Coord_X",x);
        	    map.put("Coord_Y",y);
        	    map.put("pionttext",name);  
               	map.put("FLOOR",floor);
               	persons.add(map);
               	Log.d("lxr",(String) map.get("Coord_X")+(String) map.get("Coord_Y")+(String) map.get("pionttext")+(String) map.get("FLOOR")); 
               	Log.d("lx","helloworld");
               	//	Log.d("lxr", floorName);
     	}	
	}
	} catch (Exception e) {
	e.printStackTrace();
	}
	return persons;
	}*/
	
	
	public  void readXML( PointF fromis, PointF gotois,String ffloor,String gfloor){   
		String url="http://10.103.240.77:55555/xml?2&"+String.valueOf(fromis.x)+","+String.valueOf(fromis.y)+","+ffloor+"&"+String.valueOf(gotois.x)+","+String.valueOf(gotois.y)+","+gfloor+"&"+Mallid;
	        //String url="http://10.103.241.194:55555/xml?2&"+String.valueOf(fromis.x)+","+String.valueOf(fromis.y)+","+ffloor+"&"+String.valueOf(gotois.x)+","+String.valueOf(gotois.y)+","+gfloor+"&"+Mallid;
	        Log.d("lxr",url);
	        aq.ajax(url, XmlDom.class, this, "picasaCb");           
	        ProgressDialog();
	}
	
	public void picasaCb(String url, XmlDom xml, AjaxStatus status){
		
		List<Map<String, Object>> routelist = new ArrayList<Map<String,Object>>();	
		 Element root = xml.getElement();
		    NodeList items = root.getElementsByTagName("POINT");//查找所有person节点
		  String x = null,y = null,name = null,floor = null,x1 = null,y1 = null,name1 = null,floor1 = null;
		  for (int i = 0; i < items.getLength(); i++) { 
			Element personNode = (Element) items.item(i);
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	NodeList childsNodes = personNode.getChildNodes();
	     	for (int j = 0; j < childsNodes.getLength(); j++) {
	        	Node node = (Node) childsNodes.item(j); //判断是否为元素类型          	
	        	if(node.getNodeType() == Node.ELEMENT_NODE){ 
	         		Element childNode = (Element) node;
		        	if ("X".equals(childNode.getNodeName())) { 
	        		   x=childNode.getFirstChild().getNodeValue();  
	        	   } else if ("Y".equals(childNode.getNodeName())) {
		        	  y=childNode.getFirstChild().getNodeValue();
	        	   } else if ("NAME".equals(childNode.getNodeName())) {
		        	  name=childNode.getFirstChild().getNodeValue();
		           }else if ("FLOOR".equals(childNode.getNodeName())) {
		        	  floor=childNode.getFirstChild().getNodeValue();
		           }		
	        	}	
		   }
	     	if(!x.equals(x1)||!y.equals(y1)||!name.equals(name1)||!floor.equals(floor1)){
	     		    x1=x;y1=y;name1=name;floor1=floor;
	     		    map.put("Coord_X",x);map.put("Coord_Y",y); map.put("pionttext",name); map.put("FLOOR",floor);routelist.add(map);
	               	//Log.d("lxr",(String) map.get("Coord_X")+(String) map.get("Coord_Y")+(String) map.get("pionttext")+(String) map.get("FLOOR")); 
	               	}	
		   }
		  mapLayout.DrawRoute(routelist,floorName); mapLayout.updatedrawtoroute();
          Webconnected=true;
		  mapLayout.hideOverlay2();
		 // m_pDialog.cancel();
	}
	
	
	
	@SuppressWarnings("deprecation")
	public void down_file_2(String ID,final String url,final String path) throws IOException{//下载函数 
	     int fileSize=0;
	     final ProgressDialog m_pDialog;
	     File file = new File(path);
	     if (!file.exists()) {file.mkdir();}
	  	String filename=url.substring(url.lastIndexOf("/") + 1);//获取文件名
	  	Log.d("lxr",filename);
	  	URL myURL = new URL(url);
	  	URLConnection conn =myURL.openConnection();
	    conn.connect();
	  	final InputStream is = conn.getInputStream();   
	  	fileSize = conn.getContentLength();//根据响应获取文件大小
	  	if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
	  	if (is == null) throw new RuntimeException("stream is null");
	  	final FileOutputStream fos = new FileOutputStream(path+filename);	//把数据存入路径+文件名
	  	m_pDialog = new ProgressDialog(DrawActivity.this);    //创建ProgressDialog对象
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // 设置进度条风格，风格为圆形，旋转的
        m_pDialog.setTitle("地图下载");          // 设置ProgressDialog 标题
        m_pDialog.setMessage("正在从网络端下载地图");      // 设置ProgressDialog 提示信息
        m_pDialog.setIcon(R.drawable.ic_launcher);       // 设置ProgressDialog 标题图标
        m_pDialog.setIndeterminate(false);     // 设置ProgressDialog 的进度条是否不明确
        m_pDialog.setCancelable(true); // 设置ProgressDialog 是否可以按退回按键取消
        m_pDialog.setButton("确定", new DialogInterface.OnClickListener() {       // 设置ProgressDialog 的一个Button
            public void onClick(DialogInterface dialog, int i){
                dialog.cancel();//点击“确定按钮”取消对话框
            } });
        m_pDialog.show(); // 让ProgressDialog显示
       	byte buf[] = new byte[1024*64];
        	int downLoadFileSize = 0;
            do{
    	    	int numread = 0;
				try {numread = is.read(buf);} catch (IOException e) {e.printStackTrace();}//循环读取
    	    	if (numread == -1){
    	    	     break;
        	    }
        	try {fos.write(buf, 0, numread);} catch (IOException e) {e.printStackTrace();}
        	downLoadFileSize += numread;

        	m_pDialog.setProgress(downLoadFileSize);//更新进度条
        	} while (true);
                m_pDialog.cancel(); //通知下载完成
                
        	Log.d("lxr","downloadsusses");
    	    	try{
    	    		is.close();
    	    		dialogShowOK(ID);
    	    	} catch (Exception ex){
    	    		Log.e("tag", "error: " + ex.getMessage(), ex);
    	    		 m_pDialog.cancel();
    	    	}
    	    	
     }
	 
	 private void dialogShowOK(final String ID) {  
		    new AlertDialog.Builder(this)  
		    .setTitle("地图下载")  
		    .setMessage("地图已成功下载")  
		    .setPositiveButton  
		            ("确定", new DialogInterface.OnClickListener()  
		                { public void onClick(DialogInterface dialog, int which) 
		                    {       
		                	floorName="Floor1";
						    MallDBpath=ID;
						   	mapLayout.changemap(MallDBpath, floorName);
							addfloorlist(MallDBpath);
							addwclist();
							DrawDBTool dbTool = new DrawDBTool(DrawActivity.this);
							Mallid=dbTool.getMAllid(MallDBpath);
							mapLayout.hideAll();
							//backtoschoolBtn.setVisibility(View.VISIBLE);
							floormenulist.setVisibility(View.VISIBLE);
		                    }    
		                }  
		            )
		    .show();  
		}  
	 //换地图的时候显示该地图上的路径
	 private void RouteOfMap(){
		 Log.d("lxr","RouteOfMap:"+fromDBpath+","+gotoDBpath+","+MallDBpath);
		 
		 String ff = null,gf = null;
		 PointF fc=new PointF(),gc=new PointF();
		 if(MallDBpath.equals("phone3") && (fromDBpath.equals("phone3")||gotoDBpath.equals("phone3")||!fromDBpath.equals(gotoDBpath))){
			 Log.d("lxr","室外地图");
			 ff="Floor0";gf="Floor0";
			 if(fromDBpath.equals("phone3")){
			   fc=fromCoord;
			 }else{
			   DrawDBTool dbTool = new DrawDBTool(this);
			   fc=dbTool.getSpotCoord(fromDBpath);}
			 if(gotoDBpath.equals("phone3")){
			   gc=gotoCoord;
			 }else{
			   DrawDBTool dbTool = new DrawDBTool(this);
			   gc=dbTool.getSpotCoord(gotoDBpath);}
			 
			 if(!ff.equals(floorName)){
				 floorName=ff;           mapLayout.changemap(MallDBpath,floorName);
			     mapLayout.hideAll();  	mapLayout.pinfromAtMapWithMapCoord(fc);}
			 readXML(fc,gc,ff,gf);////////////////////////////////////////////////
			// List<Map<String, Object>> routelist = readXML(fc,gc,ff,gf,MallDBpath);
			// mapLayout.DrawRoute(routelist,floorName);  		mapLayout.updatedrawtoroute();
			 
		 }else if(MallDBpath.equals(fromDBpath)||MallDBpath.equals(gotoDBpath)){
				Log.d("lxr","室内地图");
				 if(MallDBpath.equals(fromDBpath)){
					 ff=fromfloor; fc=fromCoord;
			      }else {
			    	  DrawDBTool dbTool = new DrawDBTool(this);
					  fc=dbTool.getExit(MallDBpath);ff="Floor1";	
			      }
			    	  
			     if(MallDBpath.equals(gotoDBpath)){
			    	  gf=gotofloor; gc=gotoCoord;
			      }else{
					  DrawDBTool dbTool = new DrawDBTool(this);
					  gc=dbTool.getExit(MallDBpath);gf="Floor1";
			      }
			     if(!ff.equals(floorName)){
			    	 floorName=ff;           mapLayout.changemap(MallDBpath,floorName);
			     	 mapLayout.hideAll();  	mapLayout.pinfromAtMapWithMapCoord(fc);}
			     readXML(fc,gc,ff,gf);///////////////////////////////////////////////
			     //List<Map<String, Object>> routelist = readXML(fc,gc,ff,gf,MallDBpath);
			    // mapLayout.DrawRou`te(routelist,floorName);  		mapLayout.updatedrawtoroute();
			 }else{
				 Log.d("lxr","Oh!Shit!!!!");
			 }
	 }
	 
	    @SuppressWarnings("deprecation")
		void ProgressDialog(){
	    	 //final ProgressDialog m_pDialog;
	    	
	    	m_count=0;
	    	Webconnected=false;
	    	 m_pDialog = new ProgressDialog(DrawActivity.this);    //创建ProgressDialog对象
	         m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // 设置进度条风格，风格为圆形，旋转的
	         m_pDialog.setTitle("提示");          // 设置ProgressDialog 标题
	         m_pDialog.setMessage("正在连接网络");      // 设置ProgressDialog 提示信息
	         m_pDialog.setIcon(R.drawable.ic_launcher);       // 设置ProgressDialog 标题图标
	         m_pDialog.setIndeterminate(false);     // 设置ProgressDialog 的进度条是否不明确
	         m_pDialog.setCancelable(true); // 设置ProgressDialog 是否可以按退回按键取消
	         m_pDialog.setButton("取消", new DialogInterface.OnClickListener() { // 设置ProgressDialog 的一个Button
	             public void onClick(DialogInterface dialog, int i){
	            	 aq.dismiss();
	                 dialog.cancel();//点击“确定按钮”取消对话框
	             } });
	         m_pDialog.show(); // 让ProgressDialog显示
	         final Handler mHandler = new Handler();
	         new Thread(){
                 public void run()
                 {try{   while (m_count <= 50){ // 由线程来控制进度。
                             m_pDialog.setProgress(m_count++);
                             Thread.sleep(100);
                             if(Webconnected==true||!m_pDialog.isShowing())
                            	 break;
                         }
                         m_pDialog.cancel();
                         if(m_count >=50){
                             mHandler.post(new Runnable(){
                                public void run(){
                                	 new AlertDialog.Builder(DrawActivity.this)  
                         		    .setTitle("提示")  
                         		    .setMessage("抱歉，网络连接超时！！")  
                         		    .setNegativeButton("确定", new DialogInterface.OnClickListener()  
                     		                {public void onClick(DialogInterface dialog, int which){
                     		                	 //weather_route=false;
                     		                	 Webconnected=false;
                     		                	 aq.dismiss();
                     		                }})  
                         		    .show();  
                                }
                                });
                         }
                     }
                     catch (InterruptedException e){
                         m_pDialog.cancel();
                     }
                 }
             }.start();
	    }
	    void showToast(String v){
	    	Toast toast = Toast.makeText(DrawActivity.this, v, Toast.LENGTH_SHORT); 
	    	  toast.setGravity(0|0, 80, 80); 
	    	  toast.setMargin(-0.5f, 0f); 
	    	  toast.show();
	    }

}